﻿using System;
using UnityEditor;
using UnityEngine;

namespace UFrame
{
    public class AnimatorWindow : BaseTestWindow
    {
        [MenuItem("Plateface/Animation/动画窗口")]
        static void ShowEditor()
        {

            AnimatorWindow editor = GetWindow<AnimatorWindow>();
            editor.titleContent = new GUIContent("动画调试窗口");
            editor.Show(true);
        }

        private string expression = string.Empty;



        public void Update()
        {
            this.Repaint();
        }

        public void OnGUI()
        {
            OnGUIRefresh();
        }

        protected void OnGUIRefresh()
        {
            var go = Selection.activeGameObject;
            Animator a = null;
            Animation animation = null;
            if (go != null)
            {
                a = go.GetComponent<Animator>();
                animation = go.GetComponent<Animation>();
            }

            if (go == null || (a == null && animation == null))
            {
                EditorGUILayout.HelpBox("没有选中Animator 或 Animation节点", MessageType.Info);
                return;
            }


            expression = TextField("表达式:", expression);


            if (GUILayout.Button("设置参数"))
            {
                if (a != null)
                {
                    string[] exAry = expression.Split(';');
                    foreach (var item in exAry)
                    {
                        var typeAndValue = item.Split('=');
                        SetAnimationParameter(typeAndValue[0], typeAndValue[1]);
                    }
                }
                if (animation != null)
                {
                    animation.Play(expression);
                }
            }
        }


        private void SetAnimationParameter(string name, string val)
        {
            var go = Selection.activeGameObject;

            Animator a = go.GetComponent<Animator>();

            var parameter = a.parameters;
            foreach (var p in parameter)
            {
                if (p.name != name)
                {
                    continue;
                }

                if (p.type == AnimatorControllerParameterType.Bool)
                {
                    bool bVal = Convert.ToBoolean(val);
                    a.SetBool(name, bVal);
                }

                if (p.type == AnimatorControllerParameterType.Float)
                {
                    float fVal = Convert.ToSingle(val);
                    a.SetFloat(name, fVal);
                }

                if (p.type == AnimatorControllerParameterType.Int)
                {
                    int intVal = Convert.ToInt32(val);
                    a.SetInteger(name, intVal);
                }

                if (p.type == AnimatorControllerParameterType.Trigger)
                {
                    a.SetTrigger(name);
                }
            }
        }
    }
}